import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {getDetail, getDealersQuickly, getDealers} from './api';
import {Button, Form, Row, Col, Card, Spin, Collapse, Popconfirm, Modal} from 'antd';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {conventEnumValueToString, formatAmount} from '../utils';
import {PERMISSION, hasPermissions} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, formatMessage} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import {currency} from '../Enum';
import styles from './style.css';
import DetailTable from './DetailTable';
import GoodWillSelectPanel from './GoodWillSelectPanel';
const Panel = Collapse.Panel;
const EMPTY_ARRAY = [];
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {
            laborFee: 0,
            materialFee: 0,
            totalFee: 0,
        },
        details: [],
        showPanel: false
    };

    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }

    getDetailInfo = () => {
        this.setState({loading: true});
        getDetail(this.props.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.goodwillSettlementDetails,
                    });
                this.setState({
                    loading: false
                });
            });
    }

    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                    currency: condition.currency,
                    country: condition.countryName
                }
            };
        });
    };
    onSubmit = () => {
        const isValid = newOrUpdateOrderValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data, this.state.details).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickAdd = () => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.setState({
            showPanel: true
        });
    }
    onSelectList= data => {
        const retailDetails = this.state.details || [];
        data.forEach(r => {
            const index = retailDetails.findIndex(v => v.id === r.id);
            if(index === -1)
                retailDetails.push({
                    id: r.id,
                    goodWillCode: r.goodWillCode,
                    laborFee: r.laborFee,
                    materialFee: r.materialFee,
                    totalFee: r.totalFee,
                    goodWillDetails: r.goodWillDetails,
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showPanel: false
        });
    }
    onDeleteAll = () => {
        this.setState({
            currentPanelId: '',
            details: [],
            hasOperat: true,
        });
    }
    onChangeCollapse = key => {
        this.setState({
            currentPanelId: key
        });
    }
    onClickDelete = e => {
        const id = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== id);
        if(this.state.details.length !== 0)
            this.setState({
                details: [...tmp],
                hasOperat: true,
            });
    };
    render() {
        const {data = {}, details = [], validate, loading,
            currentPanelId, hasOperat} = this.state;
        const validateDealer = !data.dealerId && validate ? 'error' : null;
        const validateCurrency = !data.currency && validate ? 'error' : null;
        const validateBrand = !data.brandId && validate ? 'error' : null;
        const validateAmount = !data.amount && validate ? 'error' : null;
        const {pagePermission, id, brands} = this.props;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const packingPanel = details.map(p => {
            const header = (
                <Row>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.goodWillCode',
                            defaultMessage: 'GoodWill编号'
                        })}: ${p.goodWillCode}`}
                    </Col>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.laborFee',
                            defaultMessage: '工时费'
                        })}: ${formatAmount(p.laborFee)}`}
                    </Col>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.materialFee',
                            defaultMessage: '材料费'
                        })}: ${formatAmount(p.materialFee)}`}
                    </Col>
                    <Col span={4}>
                        {`${formatMessage({
                            id: 'detailPage.info.totalFee',
                            defaultMessage: '费用合计'
                        })}: ${formatAmount(p.totalFee)}`}
                    </Col>
                    <Col span={2} className={`col-align-right ${styles.optionBtn}`}>
                        {<a data-id={p.id} onClick={this.onClickDelete}>{formatMessage({
                            id: 'addWorkItem.workItems.deleteBtn',
                            defaultMessage: '删除'
                        })}</a>}
                    </Col>
                </Row>
            );
            const dataSource = p.goodWillDetails || EMPTY_ARRAY;
            return (
                <Panel key={p.id} header={header} >
                    <DetailTable data={dataSource} loading={this.state.loading} />
                </Panel>
            );
        });
        const currentSelectRowKeys = details.map(item => item.id);
        const queryCondition = {
            brandId: data.brandId
        };
        const dealerComp = data.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealersQuickly}
            getDealers={getDealers}
            conditions={queryCondition}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled={true} placeholder={formatMessage({
                id: 'newPanel.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        return (
            <div className="form-standard">
                <Modal
                    title={formatMessage({
                        id: 'add.stock.modal.title',
                        defaultMessage: 'GoodWill查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <GoodWillSelectPanel
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.onSelectList} />
                </Modal>
                <Spin spinning={loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                {id && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required >
                                        {id ? `(${data.brandCode})${data.brandName}`
                                            : <WrappedSelect
                                                allowClear
                                                name="brandId"
                                                value={data.brandId}
                                                options={brands}
                                                onChange={this.handleFilterChange}/>
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        {dealerComp}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'queryPanel.form.country',
                                            defaultMessage: '国家'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.laborFee',
                                            defaultMessage: '工时费合计'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateAmount} required>
                                        {data.laborFee}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.materialFee',
                                            defaultMessage: '材料费'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateAmount} required>
                                        {data.materialFee}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.totalFee',
                                            defaultMessage: '费用合计'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateAmount} required>
                                        {data.totalFee}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.comment',
                                            defaultMessage: '业务内容'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateAmount} required>
                                        <TextInput
                                            name="comment"
                                            value={data.comment}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card><Card
                            extra={<span className={styles.optionBtn}>
                                <Button key="addBtn" size="small" onClick={this.onClickAdd}>
                                    {formatMessage({
                                        id: 'add.form.addBtn',
                                        defaultMessage: '新增'
                                    })}
                                </Button>
                                {details.length ? (<Popconfirm
                                    placement="top"
                                    key="deleteAll"
                                    onConfirm={this.onDeleteAll}
                                    title={formatMessage({
                                        id: 'add.popconfirm.delete.message',
                                        defaultMessage: '是否确认清空?'
                                    })}
                                    okText={formatMessage({
                                        id: 'add.popconfirm.confirm',
                                        defaultMessage: '确认'
                                    })}
                                    cancelText={formatMessage({
                                        id: 'add.popconfirm.cancel',
                                        defaultMessage: '取消'
                                    })}>
                                    <Button size="small" key="clearBtn">
                                        {formatMessage({
                                            id: 'add.materials.clearBtn',
                                            defaultMessage: '清空'
                                        })}
                                    </Button>
                                </Popconfirm>)
                                    : (
                                        <Button size="small" key="clearBtn">
                                            {formatMessage({
                                                id: 'add.materials.clearBtn',
                                                defaultMessage: '清空'
                                            })}
                                        </Button>
                                    )}
                            </span>}>
                            <Collapse accordion activeKey={currentPanelId} onChange={this.onChangeCollapse}>
                                {packingPanel}
                            </Collapse>
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={loading}
                        showWarning={hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : EMPTY_ARRAY;
    }
);

const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    brands: getBrands(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: (data, details) => dispatch(onSubmit(data, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
